<template>
  <div class="upload-page">
    <!-- 文件上传 -->
    <el-upload
      class="upload-demo" 
      drag  
      action="url"
      accept=".csv"
      ref="upload"
      :file-list="fileList"
      :http-request="UploadData"
      :headers="headers"
      :auto-upload="true"
      :on-error="uploadFileError"
      :on-success="uploadFileSuccess"
      :on-exceed="exceedFile"
      :show-file-list="false"
      :limit="limitnum"
      multiple
      >
      <el-button size="small" type="primary">点击上传</el-button>
    </el-upload>
    <!-- :auto-upload="false" -->
    <el-dialog
      title="重命名数据集名称"
      draggable="true"
      v-model="renameDialogVisible"
      width="30%"
      :before-close="handleRenameDialogClose">
      <el-input v-model="newFileName"  @input="validateInput" placeholder="请输入新数据集名称"></el-input>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="renameDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="confirmRename">确定</el-button>
        </span>
      </template>
    </el-dialog>
    <!-- 文件列表 -->
    <el-table
    :data="paginationTableData"
    style="width: 100%"
    @selection-change="handleSelectionChange">
    <el-table-column
      type="selection"
      width="100">
    </el-table-column>
    <el-table-column
      prop="num"
      label="编号"
      width="150">
    </el-table-column>
    <el-table-column
      prop="name"
      label="文件名称"
      >
    </el-table-column>
    <el-table-column label="操作" width="350" style="display: flex; justify-content: space-between;">
      <template v-slot:default="scope">
        <div class="button-group">
          <el-button 
          type="danger" 
          size="small" @click="deleteData(scope.row)">
            删除
          </el-button>
          <el-dropdown trigger="click">
            <span class="el-dropdown-link">
              <i class="el-icon-more">
                <el-icon><MoreFilled /></el-icon>
              </i>
            </span>
            <template v-slot:dropdown>
              <el-dropdown-menu>
                <el-dropdown-item @click="downloadFile(scope.row)">下载</el-dropdown-item>
                <el-dropdown-item @click="renameFile(scope.row)">重命名</el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </div>
      </template>
    </el-table-column>
    </el-table>

    <!-- 分页 -->
    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="currentPage"
      :page-sizes="pageSizes"
      :page-size="pageSize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="totalFile">
    </el-pagination>

    <!-- 批量删除按钮 -->
    <div class="operation" 
    :data="selectedRows"
    style="display: flex; justify-content: space-between;">
      <div class="batch-delete">
        <el-button
          type="danger"
          size="small"
          @click="deleteData(selectedRows)">批量删除
        </el-button>
      </div>  
      <div class="generation">
        <el-button
          type="danger"
          size="small"
          @click="goToGenerate">去生成
        </el-button>
      </div>
    </div>
  </div>
</template>

<script>
import { ElUpload, ElButton, ElTable, ElTableColumn, ElPagination } from 'element-plus';

export default {
  components: {
    ElUpload,
    ElButton,
    ElTable,
    ElTableColumn,
    ElPagination,
  },
  data() {
    return {
      url:"http://localhost:8080/DataSets",   //填写后端上传的服务器地址
      tableData: [], // 假设这里是你的文件列表数据
      paginationTableData:[],
      selectedRows: [], // 用户选择的文件列表
      currentPage: 1, // 当前页码
      pageSize:10,
      totalFile:0,
      renameDialogVisible: false, // 控制重命名对话框的显示
      newFileName: '', // 新文件名
      currentFile: null, // 当前需要重命名的文件对象
      fileExtension: '',
      mappingList:[],
    };
  },
  methods: {
    /*el-upload组件
       包含以下函数
       UploadData；
       uploadFileError；
       uploadFileSuccess；
       exceedFile；*/
    
    UploadData(param) {
      var fileObj = param.file;
      var form = new FormData();
      form.append("file", fileObj);
      this.$axios.post('http://localhost/api/tree/uploadData', form,{
        headers: {        
          'token': sessionStorage.getItem('token')
          }
        })
        .then((res) => {
          // 假设上传成功的逻辑处理
          if(res.data.data){
            this.$message.success('文件上传成功');
            console.log(res.data);
            param.onSuccess(res);
          }
          else{
            this.$message.error('文件上传失败：'+res.data.msg);
            console.log(res.data);
          }
        })
        .catch((error) => {
          // 假设上传失败的逻辑处理
          param.onError(error);
        });
    },
    uploadFileError(err){
      console.log("error:"+err)
      this.$message.error("上传失败:" + err)
    },
    uploadFileSuccess(response) {
      console.log("长度"+this.tableData.length)
      if(response.data.data){
        this.GetDataList()
      }else{
        this.$message.error(response.data.message+"未知错误");//文件上传错误提示
      }
    },
    exceedFile(){
      this.$message.error('只能上传'+this.limitnum+'个文件');
    },

    /*el-pagination
    包含以下函数
    getPaginationTableData；
    handleSelectionChange；
    handleSizeChange；
    handleCurrentChange；*/
    getPaginationTableData(){
      this.paginationTableData=this.tableData.slice(
        (this.currentPage-1)*this.pageSize,
        this.currentPage*this.pageSize
      );
      this.totalFile=this.tableData.length
    },
    handleSelectionChange(val) {
      this.selectedRows = val;
      console.log("handleSelectionChange");
    },
    handleSizeChange(newSize) {
      // 处理每页显示条数变化
      console.log("handleSizeChange");
      this.pageSize = newSize;
      this.currentPage = 1; // 重置到第一页
      this.getPaginationTableData();
    },
    handleCurrentChange(newPage) {
      // 处理页码变化
      console.log("handleCurrentChange");
      this.currentPage = newPage;
      this.getPaginationTableData();
    },
    //跳转到决策树详情
    goToGenerate() {
      this.$router.push({ path: '/TreeDetail'});
    },
    //数据集删除按钮
    async deleteData(dataToDelete) {
      const isSingle = !Array.isArray(dataToDelete);
      let dataNumsToDelete = isSingle ? [dataToDelete.num] : dataToDelete.map(row => row.num);
      console.log("data:"+dataNumsToDelete);
      let dataIdsToDelete = []
      let temp = this.mappingList
      dataIdsToDelete = dataNumsToDelete.map(function(index) {
        return temp[index-1].id;
      });
      const params = new URLSearchParams()
      Array.from(dataIdsToDelete).forEach(item => {
        params.append('ids', item);
      });
      this.$axios.delete(`http://localhost/api/tree/deleteData`,
      {
        headers: {        
          'token': sessionStorage.getItem('token')
          },
        data:dataIdsToDelete
        })
        .then((response) => {
          console.log(response.data);
          if (response.data.data) {
            this.$message.success('文件删除成功');
            // 从 fileList 和 tableData 移除已删除的文件
            this.GetDataList()
            if (!isSingle) {
              this.selectedRows = [];
            }
          } else {
            this.$message.error('删除失败：' + response.data.msg);
          }
        })
        .catch((error) => {
          console.error('删除文件失败', error);
          this.$message.error('删除文件失败:' + error);
        });
    },
    /*数据集重命名
    包含对话框，
    包含以下函数：
    renameFile；
    confirmRename；
    handleRenameDialogClose
    */
    validateInput(modelName) {
        const regex = /[\\?%#&$=]+/g;
        if (regex.test(this[modelName])) {
          this.$message.error('非法字符');
          this[modelName] = this[modelName].replace(regex, '');
        }
      },

    renameFile(row) {
      this.currentFile = row;
      // 分割文件名为基本名和扩展名
      const dotIndex = row.name.lastIndexOf('.');
      const baseName = dotIndex > 0 ? row.name.substring(0, dotIndex) : row.name;
      this.newFileName = baseName; // 只显示基本名供编辑
      // 保存文件的扩展名以便稍后使用
      this.fileExtension = dotIndex > 0 ? row.name.substring(dotIndex) : '';
      this.renameDialogVisible = true;
      console.log("baseName:"+baseName)
      console.log("fileExtension:"+this.fileExtension)
    },
        // 确认重命名操作
    async confirmRename() {
      if (!this.newFileName.trim()) {
        this.$message.error('文件名不能为空');
        return;
      }
      // 构造新的文件名，包括扩展名
      const newNameWithExtension = `${this.newFileName}${this.fileExtension}`;
      // 构造请求数据
      const requestData = {
        "id": this.mappingList[this.currentFile.num-1].id,
        "name": newNameWithExtension
      };
      // 发送重命名请求
      this.$axios.post('http://localhost/api/tree/renameDataSet',requestData,{
        headers: {        
          'token': sessionStorage.getItem('token')
          }
        }).then(response => {
        if (response.data.code === 200) {
          this.$message.success('文件重命名成功');
          this.renameDialogVisible = false;
          // 更新tableData中的文件名
          const fileToRename = this.tableData.find(file => file.name === this.currentFile.name);
          if (fileToRename) {
            fileToRename.name = newNameWithExtension;
          }
        } else {
          this.$message.error('重命名失败：' + response.data.message);
        }
      }).catch(error => {
        console.error('重命名请求失败', error);
        this.$message.error('重命名失败:' + error);
      });
    },
    // 对话框关闭前的处理
    handleRenameDialogClose() {
      this.renameDialogVisible = false;
    },


    //下载文件按钮
    async downloadFile(row) {
      // 假设 `row` 对象中包含了文件的唯一标识符，比如文件名或ID
      const fileName = this.mappingList[row.num - 1].id; // 或者是 `row.id`，取决于您的后端API如何识别文件
      const url = 'http://localhost/api/tree/downloadData?id='+fileName; // 需要替换成您实际的下载API URL
      this.$axios({
        url: url,
        method: 'GET',
        responseType: 'blob', // 确保响应类型为blob，以便正确处理文件流
        headers: {        
          'token': sessionStorage.getItem('token')
          }
        }).then(response => {
        // 创建一个临时URL指向响应的文件流(blob)
          if(!response){
            console.log("没有response");
          }
          let downloadUrl = window.URL.createObjectURL(new Blob([response.data]));
          let link = document.createElement('a');
          link.href = downloadUrl;
          link.style.display = 'none';
          let downloadingFileName = row.name; // 默认文件名
          downloadingFileName
          link.setAttribute('download', downloadingFileName);
          document.body.appendChild(link)
          link.click(); // 触发下载
          window.URL.revokeObjectURL(downloadUrl); // 释放掉blob对象
          this.$message.success('文件下载成功');
      }).catch(error => {
        console.error('下载文件失败:', error);
        this.$message.error('下载文件失败:' + error);
      });
    },

    //获取文件列表
    async GetDataList() {
      this.$axios.get('http://localhost/api/tree/getDataList',{
        headers: {        
          'token': sessionStorage.getItem('token')
          }
        })
        .then((response) => {
          console.log(response.data);
          if (response.data.code === 200) {
            this.tableData = response.data.data.map((item,index) => ({
                num: index + 1,
                name: item.name
            }));
            this.mappingList = response.data.data.map((item) => ({
                id: item.id
            }));
            console.log(this.tableData)
            this.getPaginationTableData()
          } else {
            console.error('获取文件列表失败', response.data.msg);
            this.$message.error('获取文件列表失败：' + response.data.msg);
          }
        })
        .catch((error) => {
          console.error('获取文件列表失败', error);
          this.$message.error('获取文件列表失败:' + error);
        });
    },
  },
  mounted(){

    this.GetDataList();

  },

};
</script>

<style scoped>
.upload-page {
  margin: 10px;
  background-color: white;
  border-radius: 8px;
  overflow: auto;
  box-shadow: 0 4px 8px rgba(0,0,0,0.1); /* 添加阴影效果 */
  padding: 10px; /* 添加内边距 */
}

.batch-delete {
  margin-top: 10px;
  text-align: left;
}
.generation{
  margin-top: 10px;
  text-align: right;
}
.delete-button{
  margin-top: 10px;

}
.el-dropdown-link {
  margin-left: 10px;
  margin-top: 5px;
  transform: scale(1.5); /* 将按钮放大1.5倍 */

}
</style>
